﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using GestaoContas.LigacaoBD;

namespace GestaoContas
{
    public partial class Ligacao : Form
    {
        private FicheiroConfiguracao _fConfig;
        private string _stringDeLigacao;

        public Ligacao()
        {
            InitializeComponent();

            _fConfig = new FicheiroConfiguracao();

            PreecheConfiguracao(_fConfig.GetConnectionStringLogin());
            textBoxPath.Text = _fConfig.GetConnectionStringBd();
        }

        /// <summary>
        /// Preence os campos da form com a configuração retirada da connection string.
        /// </summary>
        /// <param name="config">Connection string</param>
        private void PreecheConfiguracao(string config)
        {
            if(config!=null){
                string[] configString = config.Split(';');

                foreach (string s in configString)
                {
                    string[] bloco = s.Split('=');
                    if (bloco[0].Equals("Data Source"))
                        textBoxDataSource.Text = bloco[1];

                    if (bloco[0].Equals("Initial Catalog"))
                        textBoxInitialCatalog.Text = bloco[1];

                    if (bloco[0].Equals("Integrated Security"))
                        checkBoxIntegratedSecurity.Checked = true;
                }
            }
        }

        private void buttonOk_Click(object sender, EventArgs e)
        {
            _stringDeLigacao = "Data Source=" + textBoxDataSource.Text.ToString();
            _stringDeLigacao += ";Initial Catalog=" + textBoxInitialCatalog.Text.ToString();

            if (checkBoxIntegratedSecurity.Checked)
                _stringDeLigacao += ";Integrated Security=True";

            _fConfig.EscreverFicheiroConfig(_stringDeLigacao, "LigacaoLogin.cfg");
            _fConfig.EscreverFicheiroConfig(textBoxPath.Text, "LigacaoBD.cfg");

            Close();
        }

        private void buttonCancel_Click(object sender, EventArgs e)
        {
            Close();
        }


    }
}
